﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebAppPlanProduccion.Code;
using WebAppPlanProduccion.Code.Security;
using Web.Framework;

using PlanProd.Contracts.Search;
using PlanProd.Contracts;
using Web.Framework.Svc;
using System.IO;
using System.Text;
using PlanProd.ServiceFactory;

namespace WebAppPlanProduccion.App
{
    public partial class ProductoList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                HasPermissionToSeeMe(PlanProdSecurity.PRODUCTO_VER);
                if (!this.IsPostBack)
                {
                    UIHelper.LoadTemporadas(this.cboTemporada, "Todas");
                    UIHelper.LoadCalidad(this.cboCalidad, "Todas");
                }
            }
        }

        protected override void ApplySecurity()
        {
            //this.lnkSincronizar.Visible = HasPermissionFor(PlanProdSecurity.PRODUCTO_SINCRONIZAR);
            this.pnlImportar.Visible = HasPermissionFor(PlanProdSecurity.PRODUCTOS_IMPORTAR);
        }

        protected void lnkBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        //protected void lnkSincronizar_Click(object sender, EventArgs e)
        //{
        //    //try
        //    //{
        //    //    Buscar();
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    ExceptionManager.Instance.HandleException(ex);
        //    //}
        //}        

        protected void GridProductos_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                this.GridProductos.PageIndex = e.NewPageIndex;

                Buscar();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridProductos_RowCommand(object sender, GridViewCommandEventArgs e)
        {
        }

        protected void GridProductos_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }

        private void Buscar()
        {
            ServiceOptions searchOptions = new ServiceOptions();
            searchOptions.PageNumber = GridProductos.PageIndex;
            searchOptions.PageSize = GridProductos.PageSize;
            var securityContext = GetSecurityContextForDestinos();
            searchOptions.IsAdmin = BaseWebPage.IsAdmin;
            searchOptions.Operations = securityContext.Operations;

            SearchProductCriteria productSearchCriteria = new SearchProductCriteria();
            productSearchCriteria.CodigoProducto = this.txtProducto.Text;
            productSearchCriteria.CodigoColor = this.txtColor.Text;
            productSearchCriteria.TemporadaId = UIHelper.GetIntFromInputCbo(cboTemporada);
            productSearchCriteria.CalidadId = UIHelper.GetIntFromInputCbo(cboCalidad);

            List<Producto> productos = WebServiceHelper.SearchProducts(searchOptions, productSearchCriteria);

            this.GridProductos.DataSource = productos;
            this.GridProductos.DataBind();

            pnlResults.Visible = true;
            pnlAllResults.Visible = true;
        }

        protected void lnkImportar_Click(object sender, EventArgs e)
        {
            string filePath = string.Empty;
            try
            {
                if (this.fileProductos.HasFile)
                {
                    string tmpPath = HttpContext.Current.Server.MapPath("/Tmp");
                    string fileName = Guid.NewGuid().ToString();
                    filePath = Path.Combine(tmpPath, fileName);
                    this.fileProductos.SaveAs(filePath);
                    List<string> parseErrors = new List<string>();

                    // Cargar objetos de producto color
                    List<Producto> productoList = ExcelHelper.GetProductosFromExcel(filePath, parseErrors);

                    if (parseErrors.Count == 0)
                    {                        
                        IPlanProdAdmin service = ServiceFactory.GetPlanProdAdminService();
                        productoList.ForEach(p => { p.EmpresaId = BasePage.CompanyId; });
                        service.SaveProductos(WebServiceHelper.ServiceOptionsDefault, productoList);
                        masterPage.ShowMessage("Los productos se generaron correctamente", WebMessageType.Notification);                      
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();
                        string separador = string.Empty;
                        foreach (string parseError in parseErrors)
                        {
                            builder.Append(separador);
                            builder.AppendLine(parseError);
                            separador = "<br />";
                        }

                        masterPage.ShowMessage(builder.ToString(), WebMessageType.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }
    }
}